<template>
  <teleport to="body">
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" v-if="visible">
      <div class="bg-white rounded-xl w-full max-w-6xl max-h-[90vh] overflow-hidden flex flex-col">
        <div class="p-6 border-b border-gray-100 flex justify-between items-center">
          <h3 class="text-xl font-bold">媒体库</h3>
          <div class="flex items-center gap-3">
            <div class="relative">
              <input 
                type="text" 
                placeholder="搜索图片..." 
                class="form-input pl-10 w-64"
                v-model="searchKeyword"
                @keyup.enter="filterImages"
              >
              <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            </div>
            <button class="btn btn-secondary" @click="uploadNewImage">
              <i class="fa fa-upload mr-1"></i>
              <span>上传图片</span>
            </button>
            <button class="text-gray-400 hover:text-gray-600" @click="$emit('close')">
              <i class="fa fa-times"></i>
            </button>
          </div>
        </div>
        
        <div class="flex-1 overflow-hidden flex">
          <!-- 左侧分类 -->
          <div class="w-48 border-r border-gray-100 bg-gray-50 overflow-y-auto">
            <div class="p-3">
              <button 
                class="w-full text-left px-3 py-2 rounded-md text-sm"
                :class="activeCategory === 'all' ? 'bg-primary text-white' : 'text-gray-700 hover:bg-gray-200'"
                @click="activeCategory = 'all'"
              >
                全部图片
              </button>
            </div>
            
            <div class="border-t border-gray-200 p-3">
              <h4 class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">图片分类</h4>
              <div class="space-y-1">
                <button 
                  class="w-full text-left px-3 py-2 rounded-md text-sm"
                  :class="activeCategory === 'product' ? 'bg-primary text-white' : 'text-gray-700 hover:bg-gray-200'"
                  @click="activeCategory = 'product'"
                >
                  <i class="fa fa-cube mr-2 text-xs"></i>
                  产品图片
                </button>
                <button 
                  class="w-full text-left px-3 py-2 rounded-md text-sm"
                  :class="activeCategory === 'banner' ? 'bg-primary text-white' : 'text-gray-700 hover:bg-gray-200'"
                  @click="activeCategory = 'banner'"
                >
                  <i class="fa fa-picture-o mr-2 text-xs"></i>
                  轮播图片
                </button>
                <button 
                  class="w-full text-left px-3 py-2 rounded-md text-sm"
                  :class="activeCategory === 'article' ? 'bg-primary text-white' : 'text-gray-700 hover:bg-gray-200'"
                  @click="activeCategory = 'article'"
                >
                  <i class="fa fa-file-image-o mr-2 text-xs"></i>
                  文章图片
                </button>
                <button 
                  class="w-full text-left px-3 py-2 rounded-md text-sm"
                  :class="activeCategory === 'other' ? 'bg-primary text-white' : 'text-gray-700 hover:bg-gray-200'"
                  @click="activeCategory = 'other'"
                >
                  <i class="fa fa-ellipsis-h mr-2 text-xs"></i>
                  其他图片
                </button>
              </div>
            </div>
            
            <div class="border-t border-gray-200 p-3">
              <h4 class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">最近上传</h4>
              <div class="space-y-1">
                <button 
                  class="w-full text-left px-3 py-2 rounded-md text-sm text-gray-700 hover:bg-gray-200"
                  @click="filterByDate('today')"
                >
                  今天
                </button>
                <button 
                  class="w-full text-left px-3 py-2 rounded-md text-sm text-gray-700 hover:bg-gray-200"
                  @click="filterByDate('week')"
                >
                  本周
                </button>
                <button 
                  class="w-full text-left px-3 py-2 rounded-md text-sm text-gray-700 hover:bg-gray-200"
                  @click="filterByDate('month')"
                >
                  本月
                </button>
              </div>
            </div>
          </div>
          
          <!-- 右侧图片列表 -->
          <div class="flex-1 overflow-y-auto p-4">
            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
              <div 
                v-for="image in filteredImages" 
                :key="image.id"
                class="group relative cursor-pointer"
              >
                <div class="aspect-square bg-gray-100 rounded overflow-hidden">
                  <img 
                    :src="image.url" 
                    :alt="image.name"
                    class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
                  >
                </div>
                <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-40 transition-colors flex items-center justify-center opacity-0 group-hover:opacity-100">
                  <div class="w-8 h-8 rounded-full bg-white flex items-center justify-center">
                    <i 
                      class="fa" 
                      :class="isSelected(image.url) ? 'fa-check text-primary' : 'fa-plus text-gray-700'"
                    ></i>
                  </div>
                </div>
                <div 
                  class="absolute top-2 right-2 w-6 h-6 rounded-full bg-primary flex items-center justify-center text-white"
                  v-if="isSelected(image.url)"
                >
                  <i class="fa fa-check text-xs"></i>
                </div>
                <div class="mt-1 text-xs text-gray-500 truncate">{{ image.name }}</div>
              </div>
              
              <!-- 上传区域 -->
              <div class="aspect-square border-2 border-dashed border-gray-300 rounded flex flex-col items-center justify-center text-gray-400 hover:border-primary hover:text-primary cursor-pointer">
                <i class="fa fa-cloud-upload text-2xl mb-2"></i>
                <span class="text-xs">上传新图片</span>
                <input type="file" class="sr-only" accept="image/*" id="media-upload">
                <label for="media-upload" class="absolute inset-0 cursor-pointer"></label>
              </div>
            </div>
            
            <!-- 无结果提示 -->
            <div v-if="filteredImages.length === 0 && !loading" class="text-center py-16">
              <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                <i class="fa fa-picture-o text-2xl text-gray-400"></i>
              </div>
              <h3 class="text-lg font-medium mb-2">未找到图片</h3>
              <p class="text-gray-500 max-w-md mx-auto">
                没有找到符合当前条件的图片，请尝试调整筛选条件或上传新图片
              </p>
            </div>
            
            <!-- 加载中提示 -->
            <div v-if="loading" class="text-center py-16">
              <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                <i class="fa fa-spinner fa-spin text-2xl text-gray-400"></i>
              </div>
              <p class="text-gray-500">加载中...</p>
            </div>
            
            <!-- 分页 -->
            <div v-if="filteredImages.length > 0 && !loading" class="mt-6 flex items-center justify-center">
              <div class="flex items-center gap-2">
                <button 
                  class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
                  :disabled="currentPage === 1"
                  @click="currentPage = currentPage - 1"
                >
                  <i class="fa fa-chevron-left text-xs"></i>
                </button>
                
                <button 
                  v-for="page in visiblePages" 
                  :key="page"
                  class="w-8 h-8 flex items-center justify-center rounded"
                  :class="currentPage === page ? 'bg-primary text-white' : 'border border-gray-300 hover:bg-gray-50'"
                  @click="currentPage = page"
                >
                  {{ page }}
                </button>
                
                <button 
                  class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
                  :disabled="currentPage === totalPages"
                  @click="currentPage = currentPage + 1"
                >
                  <i class="fa fa-chevron-right text-xs"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <div class="p-4 border-t border-gray-100 flex justify-end gap-3 bg-gray-50">
          <div class="text-sm text-gray-500 mr-auto">
            已选择 <span class="font-medium text-primary">{{ selectedImages.length }}</span> 张图片
          </div>
          <button class="btn btn-secondary" @click="$emit('close')">
            <i class="fa fa-times"></i>
            <span>取消</span>
          </button>
          <button 
            class="btn btn-primary" 
            @click="$emit('confirm', selectedImages)"
            :disabled="selectedImages.length === 0"
          >
            <i class="fa fa-check"></i>
            <span>确认选择</span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { defineProps, defineEmits, ref, computed, watch } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  selectedImages: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['close', 'confirm'])

// 媒体库状态
const searchKeyword = ref('')
const activeCategory = ref('all')
const currentPage = ref(1)
const pageSize = ref(24)
const loading = ref(false)
const selectedImages = ref([...props.selectedImages])

// 模拟媒体库图片数据
const mediaImages = ref([
  { id: 1, name: 'product-01.jpg', url: 'https://picsum.photos/id/1005/400/400', category: 'product', uploadTime: '2023-06-20' },
  { id: 2, name: 'product-02.jpg', url: 'https://picsum.photos/id/1012/400/400', category: 'product', uploadTime: '2023-06-20' },
  { id: 3, name: 'product-03.jpg', url: 'https://picsum.photos/id/1025/400/400', category: 'product', uploadTime: '2023-06-19' },
  { id: 4, name: 'product-04.jpg', url: 'https://picsum.photos/id/1074/400/400', category: 'product', uploadTime: '2023-06-18' },
  { id: 5, name: 'product-05.jpg', url: 'https://picsum.photos/id/1027/400/400', category: 'product', uploadTime: '2023-06-17' },
  { id: 6, name: 'banner-01.jpg', url: 'https://picsum.photos/id/1048/400/400', category: 'banner', uploadTime: '2023-06-16' },
  { id: 7, name: 'banner-02.jpg', url: 'https://picsum.photos/id/1060/400/400', category: 'banner', uploadTime: '2023-06-15' },
  { id: 8, name: 'banner-03.jpg', url: 'https://picsum.photos/id/1067/400/400', category: 'banner', uploadTime: '2023-06-14' },
  { id: 9, name: 'article-01.jpg', url: 'https://picsum.photos/id/1068/400/400', category: 'article', uploadTime: '2023-06-13' },
  { id: 10, name: 'article-02.jpg', url: 'https://picsum.photos/id/1071/400/400', category: 'article', uploadTime: '2023-06-12' },
  { id: 11, name: 'article-03.jpg', url: 'https://picsum.photos/id/1080/400/400', category: 'article', uploadTime: '2023-06-11' },
  { id: 12, name: 'other-01.jpg', url: 'https://picsum.photos/id/1082/400/400', category: 'other', uploadTime: '2023-06-10' },
  { id: 13, name: 'other-02.jpg', url: 'https://picsum.photos/id/1083/400/400', category: 'other', uploadTime: '2023-06-09' },
  { id: 14, name: 'product-06.jpg', url: 'https://picsum.photos/id/1084/400/400', category: 'product', uploadTime: '2023-06-08' },
  { id: 15, name: 'product-07.jpg', url: 'https://picsum.photos/id/1085/400/400', category: 'product', uploadTime: '2023-06-07' },
  { id: 16, name: 'product-08.jpg', url: 'https://picsum.photos/id/1086/400/400', category: 'product', uploadTime: '2023-06-06' },
  { id: 17, name: 'banner-04.jpg', url: 'https://picsum.photos/id/1088/400/400', category: 'banner', uploadTime: '2023-06-05' },
  { id: 18, name: 'banner-05.jpg', url: 'https://picsum.photos/id/1090/400/400', category: 'banner', uploadTime: '2023-06-04' },
  { id: 19, name: 'article-04.jpg', url: 'https://picsum.photos/id/1091/400/400', category: 'article', uploadTime: '2023-06-03' },
  { id: 20, name: 'article-05.jpg', url: 'https://picsum.photos/id/1092/400/400', category: 'article', uploadTime: '2023-06-02' },
  { id: 21, name: 'other-03.jpg', url: 'https://picsum.photos/id/1093/400/400', category: 'other', uploadTime: '2023-06-01' },
  { id: 22, name: 'other-04.jpg', url: 'https://picsum.photos/id/1094/400/400', category: 'other', uploadTime: '2023-05-31' },
  { id: 23, name: 'product-09.jpg', url: 'https://picsum.photos/id/1096/400/400', category: 'product', uploadTime: '2023-05-30' },
  { id: 24, name: 'product-10.jpg', url: 'https://picsum.photos/id/1097/400/400', category: 'product', uploadTime: '2023-05-29' },
  { id: 25, name: 'product-11.jpg', url: 'https://picsum.photos/id/1098/400/400', category: 'product', uploadTime: '2023-05-28' },
  { id: 26, name: 'product-12.jpg', url: 'https://picsum.photos/id/1099/400/400', category: 'product', uploadTime: '2023-05-27' },
  { id: 27, name: 'banner-06.jpg', url: 'https://picsum.photos/id/1100/400/400', category: 'banner', uploadTime: '2023-05-26' }
])

// 监听外部选中图片变化
watch(
  () => props.selectedImages,
  (newVal) => {
    selectedImages.value = [...newVal]
  },
  { deep: true }
)

// 筛选后的图片
const filteredImages = computed(() => {
  return mediaImages.value.filter(image => {
    // 分类筛选
    if (activeCategory.value !== 'all' && image.category !== activeCategory.value) return false
    
    // 关键词筛选
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      if (!image.name.toLowerCase().includes(keyword)) {
        return false
      }
    }
    
    return true
  })
})

// 分页后的图片
const paginatedImages = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return filteredImages.value.slice(startIndex, startIndex + pageSize.value)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredImages.value.length / pageSize.value) || 1
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const endPage = Math.min(totalPages.value, startPage + maxVisible - 1)
  
  // 调整起始页，确保显示足够的页码
  if (endPage - startPage + 1 < maxVisible) {
    startPage = Math.max(1, endPage - maxVisible + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})

// 检查图片是否被选中
const isSelected = (url) => {
  return selectedImages.value.includes(url)
}

// 筛选图片
const filterImages = () => {
  currentPage.value = 1
}

// 按日期筛选
const filterByDate = (period) => {
  // 实际项目中实现按日期筛选逻辑
  currentPage.value = 1
  console.log(`筛选${period}的图片`)
}

// 上传新图片
const uploadNewImage = () => {
  // 实际项目中实现上传逻辑
  alert('打开图片上传对话框')
}

// 点击图片切换选中状态
const toggleImageSelection = (url) => {
  const index = selectedImages.value.indexOf(url)
  if (index === -1) {
    selectedImages.value.push(url)
  } else {
    selectedImages.value.splice(index, 1)
  }
}
</script>